from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone


class MapLocation(models.Model):
    """
    地图位置信息模型
    """
    name = models.CharField(max_length=200, verbose_name="活动名称")
    address = models.TextField(verbose_name="详细地址")
    latitude = models.FloatField(verbose_name="纬度")
    longitude = models.FloatField(verbose_name="经度")
    description = models.TextField(blank=True, null=True, verbose_name="活动描述")
    category = models.CharField(max_length=50, verbose_name="活动类别", choices=[
        ('salon', '线下沙龙'),
        ('conference', '会议'),
        ('market', '市集'),
        ('exhibition', '展览'),
        ('performance', '演出'),
        ('sports', '体育'),
        ('education', '教育'),
        ('other', '其他'),
    ], default='other')
    is_active = models.BooleanField(default=True, verbose_name="是否启用")
    created_by = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="创建者")
    created_at = models.DateTimeField(default=timezone.now, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        verbose_name = "活动位置"
        verbose_name_plural = "活动位置"
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.name} - {self.address}"


class MapRoute(models.Model):
    """
    地图路线规划模型
    """
    name = models.CharField(max_length=200, verbose_name="路线名称")
    start_location = models.ForeignKey(
        MapLocation, 
        on_delete=models.CASCADE, 
        related_name='routes_as_start',
        verbose_name="起点"
    )
    end_location = models.ForeignKey(
        MapLocation, 
        on_delete=models.CASCADE, 
        related_name='routes_as_end',
        verbose_name="终点"
    )
    waypoints = models.JSONField(default=list, blank=True, verbose_name="途经点")
    travel_mode = models.CharField(max_length=20, verbose_name="出行方式", choices=[
        ('driving', '驾车'),
        ('walking', '步行'),
        ('transit', '公交'),
        ('bicycling', '骑行'),
    ], default='driving')
    distance = models.FloatField(null=True, blank=True, verbose_name="距离(公里)")
    duration = models.IntegerField(null=True, blank=True, verbose_name="时间(分钟)")
    route_data = models.JSONField(default=dict, blank=True, verbose_name="路线数据")
    is_favorite = models.BooleanField(default=False, verbose_name="是否收藏")
    created_by = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="创建者")
    created_at = models.DateTimeField(default=timezone.now, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        verbose_name = "地图路线"
        verbose_name_plural = "地图路线"
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.name}: {self.start_location.name} → {self.end_location.name}"


class TencentMapConfig(models.Model):
    """
    腾讯地图API配置模型
    """
    api_key = models.CharField(max_length=200, verbose_name="API密钥")
    secret_key = models.CharField(max_length=200, blank=True, null=True, verbose_name="密钥")
    service_name = models.CharField(max_length=100, verbose_name="服务名称")
    is_active = models.BooleanField(default=True, verbose_name="是否启用")
    daily_quota = models.IntegerField(default=10000, verbose_name="每日配额")
    used_quota = models.IntegerField(default=0, verbose_name="已用配额")
    last_reset_date = models.DateField(default=timezone.now, verbose_name="上次重置日期")
    created_at = models.DateTimeField(default=timezone.now, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        verbose_name = "腾讯地图配置"
        verbose_name_plural = "腾讯地图配置"
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.service_name} - {'启用' if self.is_active else '禁用'}"

    def reset_daily_quota(self):
        """重置每日配额"""
        today = timezone.now().date()
        if self.last_reset_date < today:
            self.used_quota = 0
            self.last_reset_date = today
            self.save()


class MapSearchHistory(models.Model):
    """
    地图搜索历史模型
    """
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="用户")
    search_keyword = models.CharField(max_length=200, verbose_name="搜索关键词")
    search_location = models.CharField(max_length=200, blank=True, null=True, verbose_name="搜索区域")
    result_count = models.IntegerField(default=0, verbose_name="结果数量")
    search_time = models.DateTimeField(default=timezone.now, verbose_name="搜索时间")

    class Meta:
        verbose_name = "搜索历史"
        verbose_name_plural = "搜索历史"
        ordering = ['-search_time']

    def __str__(self):
        return f"{self.user.username} - {self.search_keyword}"
